package com.chatplus.application.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chatplus.application.domain.entity.account.UserEntity;
import com.chatplus.application.domain.entity.chat.ChatRoleEntity;
import com.chatplus.application.domain.request.UserChatRoleUpdateRequest;
import com.chatplus.application.domain.response.ChatRoleDetailResponse;
import com.chatplus.application.service.account.UserService;
import com.chatplus.application.service.chat.ChatRoleService;
import com.chatplus.application.web.basecontroller.BaseController;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/role")
public class ChatRoleApiController extends BaseController {

    private final ChatRoleService chatRoleService;
    private final UserService userService;

    public ChatRoleApiController(ChatRoleService chatRoleService, UserService userService) {
        this.chatRoleService = chatRoleService;
        this.userService = userService;
    }

    @GetMapping("/list")
    @SaIgnore
    public List<ChatRoleDetailResponse> list(@RequestParam(value = "user_id", required = false) Long userId, @RequestParam(value = "all", required = false, defaultValue = "false") boolean all) {
        LambdaQueryWrapper<ChatRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (!all && userId != null && userId > 0) {
            UserEntity user = userService.getById(userId);
            Object[] roleIds = user.getChatRoles().toArray();
            queryWrapper.eq(ChatRoleEntity::getEnable, true);
            queryWrapper.in(ChatRoleEntity::getMarker, roleIds);
        }
        queryWrapper.orderByAsc(ChatRoleEntity::getSortNum);
        List<ChatRoleEntity> list = chatRoleService.list(queryWrapper);
        List<ChatRoleDetailResponse> responseList = new ArrayList<>();
        for (ChatRoleEntity entity : list) {
            ChatRoleDetailResponse response = BeanUtil.copyProperties(entity, ChatRoleDetailResponse.class, "createdAt", "updatedAt");
            response.setKey(entity.getMarker());
            response.setCreatedAt(entity.getCreatedAt().getEpochSecond());
            response.setUpdatedAt(entity.getUpdatedAt().getEpochSecond());
            responseList.add(response);
        }
        return responseList;
    }

    @PostMapping("/update")
    public boolean update(@RequestBody UserChatRoleUpdateRequest request) {
        UserEntity user = userService.getById(getUserId());
        user.setChatRoles(request.getKeys());
        return userService.updateById(user);
    }

}
